import { Message } from "element-ui";
import { setStore, getStore } from "@/utils/store";
import { validatenull } from "@/utils/validate";
import {
  saveMenuInCollect,
  getMenuInCollectList,
  removeMenuInCollect,
  getMenuInClickList,
  saveMenuInClick,
} from "@/api/worktable/worktable";
// import { deepClone } from "@/utils/util";
import route from "@/router/index";
import views from "@/router/views/";
import { resetRouter } from "@/router/";
// import website from "@/config/website";
import { filterAsyncRouter } from "@/utils/router";
import {
  loginByUsername,
  logout,
  refreshToken,
  getUser,
  getButtons,
} from "@/api/user/user";
import { getRoutes } from "@/api/system/menu";
// import md5 from "js-md5";

// function addPath(ele, first) {
//   const menu = website.menu;
//   const propsConfig = menu.props;
//   const propsDefault = {
//     label: propsConfig.label || "name",
//     path: propsConfig.path || "path",
//     icon: propsConfig.icon || "icon",
//     children: propsConfig.children || "children",
//     redirect: propsConfig.redirect || "redirect",
//   };
//   const icon = ele[propsDefault.icon];
//   ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
//   const isChild =
//     ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
//   if (!isChild) {
//     ele[propsDefault.redirect] = "";
//     ele[propsDefault.children] = [];
//   } else {
//     ele[propsDefault.redirect] = ele[propsDefault.children][0].ptah;
//   }
//   if (!isChild && first && !isURL(ele[propsDefault.path])) {
//     ele[propsDefault.path] = ele[propsDefault.path] + "/index";
//   } else {
//     ele[propsDefault.children].forEach((child) => {
//       addPath(child);
//     });
//   }
// }
const user = {
  state: {
    tenantId: getStore({ name: "tenantId" }) || "",
    userInfo: getStore({ name: "userInfo" }) || "",
    permission: getStore({ name: "permission" }) || {},
    roles: [],
    menuId: {},
    token: getStore({ name: "token" }) || "",
    refreshToken: getStore({ name: "refreshToken" }) || "",
    allMenu: getStore({ name: "allMenu" }) || [],
    asyncRoute: getStore({ name: "asyncRoute" }) || [],
    activeMenu: getStore({ name: "activeMenu" }) || [],
    collectMenus: getStore({ name: "collectMenus" }) || [],
    factoryId: getStore({ name: "factoryId" }) || "0",
    factoryList: getStore({ name: "factoryList" }) || [],
    recommonMenuList: getStore({ name: "recommonMenuList" }) || [],
    account: getStore({ name: "account" }) || "",
    password: getStore({ name: "password" }) || "",
    changeState: false,
  },
  actions: {
    //根据用户名登录
    LoginByUsername({ dispatch, commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginByUsername(
          userInfo.username,
          userInfo.password,
          userInfo.captchaVerification
        )
          .then(async (res) => {
            console.log(res, dispatch, commit, ">>>>>>>>>>.");
            const data = res.data;
            // if (data.error_description) {
            //   Message({
            //     message: data.error_description,
            //     type: "error",
            //   });
            // } else {
            commit("SET_TOKEN", data.accessToken);
            commit("SET_REFRESH_TOKEN", data.refreshToken);
            const result = await dispatch("GetMenu", true);
            resolve();
            if (result.length) {
              // dispatch("SetRouter", result);
              resolve();
            }
            // }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    SetRouter({ dispatch }, result) {
      resetRouter();
      let list = filterAsyncRouter(result, true);
      console.log(list, dispatch, "result111");
      list.push({
        path: "*",
        redirect: "/404",
        hidden: true,
      });
      list.forEach((item) => {
        route.addRoute(item);
      });
    },
    //刷新token
    refreshToken({ state, commit }, userInfo) {
      window.console.log("handle refresh token");
      return new Promise((resolve, reject) => {
        refreshToken(
          state.refreshToken,
          state.tenantId,
          !validatenull(userInfo) ? userInfo.deptId : state.userInfo.dept_id,
          !validatenull(userInfo) ? userInfo.roleId : state.userInfo.role_id
        )
          .then((res) => {
            const data = res.data;
            commit("SET_TOKEN", data.access_token);
            commit("SET_REFRESH_TOKEN", data.refresh_token);
            commit("SET_USER_INFO", data);
            resolve(res.status == 200);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_USER_INFO", "");
            commit("SET_ROLES", []);
            commit("SET_FACTORY_ID", "0");
            commit("SET_TAG_LIST", []);
            commit("DEL_ALL_TAG");
            commit("SET_All_MENU", []);
            commit("SET_ACTIVE_MENU", []);
            commit("SET_ASYNC_ROUTER", []);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //注销session
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        commit("SET_USER_INFO", "");
        commit("SET_ROLES", []);
        commit("SET_TAG_LIST", []);
        commit("DEL_ALL_TAG");
        commit("SET_All_MENU", []);
        commit("SET_ACTIVE_MENU", []);
        commit("SET_ASYNC_ROUTER", []);
        resolve();
      });
    },
    //获取系统菜单
    GetMenu({ commit, dispatch }) {
      return new Promise((resolve) => {
        getRoutes().then((res) => {
          console.log(res, "-===================");
          // const list = handleTree(res.data);
          // console.log(list, "-===================");
          const menusList = res.data.menus;

          if (!menusList.length) {
            Message({
              type: "error",
              message: "登录账户无角色信息，请联系管理员",
              duration: 1500,
            });
            resolve([]);
            dispatch("FedLogOut");
          } else {
            commit("SET_USER_INFO", res.data.user);
            commit("SET_ASYNC_ROUTER", []);
            commit("SET_All_MENU", [...views]);
            resolve();
            // let menu = deepClone(menusList);
            // if (menu && menu.length > 0) {
            //   menu.forEach((ele) => {
            //     addPath(ele, true);
            //   });
            //   commit("SET_ASYNC_ROUTER", menu);
            //   commit("SET_All_MENU", [...views, ...menu]);
            //   // dispatch("GetButtons");
            //   resolve(menu);
            // }
          }
        });
      });
    },
    //收藏菜单
    SaveMenuInCollect({ dispatch }, id) {
      return new Promise((resolve) => {
        saveMenuInCollect(id).then((res) => {
          if (res.data.code != 200) return resolve(false);
          resolve(true);
          dispatch("GetMenuInCollectList");
        });
      });
    },
    //获取收藏菜单
    GetMenuInCollectList({ commit }) {
      return new Promise((resolve) => {
        getMenuInCollectList().then((res) => {
          if (res.data.code != 200) return;
          commit("SET_COLLECT_MENUS", res.data.data);
          resolve();
        });
      });
    },
    //移除收藏菜单
    RemoveMenuInCollect({ dispatch }, id) {
      return new Promise((resolve) => {
        removeMenuInCollect(id).then(() => {
          dispatch("GetMenuInCollectList");
          resolve(true);
        });
      });
    },
    // 推荐菜单
    GetMenuInClickList({ commit }) {
      return new Promise((resolve) => {
        getMenuInClickList().then((res) => {
          if (res.data.code != 200) return;
          commit("SET_RECMMON_MENU_LIST", res.data.data);
          resolve();
        });
      });
    },
    // 推荐菜单
    SaveMenuInClick({ commit }, id) {
      console.log(commit);
      return new Promise((resolve) => {
        saveMenuInClick(id).then((res) => {
          if (res.data.code != 200) return;
          resolve();
        });
      });
    },
    // 获取用户工厂列表
    GetFactoryList({ commit }, id) {
      return new Promise((resolve) => {
        getUser(id).then((res) => {
          if (res.data.code != 200) return;
          let list = res.data.data.factoryList;
          list.forEach((item) => {
            item.value = item.factoryId;
            item.label = item.factoryName;
          });
          commit("SET_FACTORY_LIST", list);
          resolve();
        });
      });
    },
    //获取系统按钮
    GetButtons({ commit }) {
      return new Promise((resolve) => {
        getButtons().then((res) => {
          const data = res.data.data;
          let obj = {};
          if (data.length) {
            data.forEach((item) => {
              let routeName = item.path.split("/").pop();
              if (item.children && item.children.length > 0) {
                obj[routeName] = item.children.map((val) => val.alias);
              }
            });
          }
          commit("SET_PERMISSION", obj);
          resolve();
        });
      });
    },
  },
  mutations: {
    SET_CHANGESTATE: (state, changeState) => {
      state.changeState = changeState;
    },
    SET_FACTORY_LIST: (state, factoryList) => {
      state.factoryList = factoryList;
      setStore({ name: "factoryList", content: state.factoryList });
    },
    SET_RECMMON_MENU_LIST: (state, recommonMenuList) => {
      state.recommonMenuList = recommonMenuList;
      setStore({ name: "recommonMenuList", content: state.recommonMenuList });
    },
    SET_ACCOUNT: (state, account) => {
      state.account = account;
      setStore({ name: "account", content: state.account });
    },
    SET_PASSWORD: (state, password) => {
      state.password = password;
      setStore({ name: "password", content: state.password });
    },

    SET_FACTORY_ID: (state, id) => {
      state.factoryId = id;
      setStore({ name: "factoryId", content: state.factoryId });
    },
    SET_COLLECT_MENUS: (state, collectMenus) => {
      state.collectMenus = collectMenus;
      setStore({ name: "collectMenus", content: state.collectMenus });
    },
    SET_ACTIVE_MENU: (state, activeMenu) => {
      state.activeMenu = activeMenu;
      setStore({ name: "activeMenu", content: state.activeMenu });
    },
    SET_All_MENU: (state, allMenu) => {
      state.allMenu = allMenu;
      setStore({ name: "allMenu", content: state.allMenu });
    },
    SET_ASYNC_ROUTER: (state, asyncRoute) => {
      state.asyncRoute = asyncRoute;
      setStore({ name: "asyncRoute", content: state.asyncRoute });
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
      setStore({ name: "token", content: state.token });
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken;
      setStore({ name: "refreshToken", content: state.refreshToken });
    },
    SET_TENANT_ID: (state, tenantId) => {
      state.tenantId = tenantId;
      setStore({ name: "tenantId", content: state.tenantId });
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
      setStore({ name: "userInfo", content: state.userInfo });
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      state.permission = permission;
      setStore({ name: "permission", content: state.permission });
    },
  },
};
export default user;
